package main.database;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.and;

import com.mongodb.client.MongoCursor;
import main.GlobalConfig;
import org.bson.Document;

public class CommentThumbHelper {
    public static void commentThumb(String uuid, String commentId, String gesture) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfThumbToComment);

        Document filter = new Document("uuid", uuid).append("commentid", commentId);
        long count = collection.countDocuments(filter);
        if (count == 0) {
            filter.append("gesture", gesture);
            collection.insertOne(filter);
        }
        else {
            Document value = new Document("gesture", gesture);
            Document query = new Document("$set", value);
            collection.updateOne(filter, query);
        }
    }

    public static long getCommentThumbupCount(String commentId) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfThumbToComment);
        Document filter = new Document("commentid", commentId).append("gesture", "up");
        return collection.countDocuments(filter);
    }

    public static long getCommentThumbdownCount(String commentId) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfThumbToComment);
        Document filter = new Document("commentid", commentId).append("gesture", "down");
        return collection.countDocuments(filter);
    }

    public static String getCommentGestureFromUUID(String commentId, String uuid) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfThumbToComment);
        FindIterable<Document> findIterable = collection.find(and(eq("commentid", commentId), eq("uuid", uuid)));
        MongoCursor<Document> cursor = findIterable.iterator();

        String result = "none";
        if(cursor.hasNext()) {
            result = cursor.next().get("gesture").toString();
        }

        return result;
    }
}
